package com.adamfass.jmeutil;

import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jmex.physics.DynamicPhysicsNode;
import com.jmex.physics.Joint;
import com.jmex.physics.PhysicsSpace;

public class Constraints {
  private Constraints() {
    throw new RuntimeException("This class should not be instantiated.");
  }
  
  public interface Constraint {
    public Joint getJoint(PhysicsSpace physicsSpace);
  }
  
  public static Constraint allowTranslation(final Vector3f axis) {
    return new Constraint() {
      public Joint getJoint(PhysicsSpace physicsSpace) {
        final Joint joint = physicsSpace.createJoint();
        joint.createTranslationalAxis().setDirection(axis);
        return joint;
      }
    };
  }
  
  public static void addToNodeWithConstraints(
      DynamicPhysicsNode node, Node parent, PhysicsSpace physicsSpace, 
      Constraint... constraints) {
    assert constraints.length > 0;
    
    DynamicPhysicsNode lastAttachedNode = null;
    for (int i = 0; i < constraints.length; ++i) {
      final DynamicPhysicsNode nodeToAttach;
      if (i == constraints.length - 1) {
        nodeToAttach = node;
      } else {
        nodeToAttach = physicsSpace.createDynamicNode();
      }
      
      parent.attachChild(nodeToAttach);
      if (i == 0) {        
        constraints[i].getJoint(physicsSpace).attach(nodeToAttach);
      } else {
        constraints[i].getJoint(physicsSpace).attach(
            lastAttachedNode, nodeToAttach);
      }
      lastAttachedNode = nodeToAttach;
    }
  }
          
}
